package com.joe.demo.chat.protocol;

import com.joe.demo.chat.message.Message;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageCodec;
import lombok.extern.slf4j.Slf4j;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.List;

/**
 * @Description 编解码
 * @Author gaojw
 * @Date 2024-08-30
 */
@Slf4j
public class MessageCodec extends ByteToMessageCodec<Message> {

    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, Message message, ByteBuf byteBuf) throws Exception {
        // 4 字节 魔数
        byteBuf.writeBytes(new byte[]{1,2,3,4});
        // 1 字节 版本
        byteBuf.writeByte(1);
        // 1 字节 序列化的方式 jdk 0 json 1
        byteBuf.writeByte(0);
        // 1 字节 指令类型
        byteBuf.writeByte(message.getMessageType());
        // 4 字节 请求序号
        byteBuf.writeInt(message.getSequenceId());
        // 无意义， 对齐填充
        byteBuf.writeByte(0xff);

        final ByteArrayOutputStream bos = new ByteArrayOutputStream();
        final ObjectOutputStream oos = new ObjectOutputStream(bos);
        oos.writeObject(message);
        final byte[] bytes = bos.toByteArray();
        // 4 字节 长度
        byteBuf.writeInt(bytes.length);
        // 获取内容的字节数组
        byteBuf.writeBytes(bytes);
    }

    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception {
        final int magicNum = byteBuf.readInt();
        final byte version = byteBuf.readByte();
        final byte serializerType = byteBuf.readByte();
        final byte messageType = byteBuf.readByte();
        final int sequenceId = byteBuf.readInt();
        byteBuf.readByte();
        final int contentLength = byteBuf.readInt();

        final byte[] bytes = new byte[contentLength];
        byteBuf.readBytes(bytes, 0, contentLength);
        if (serializerType == 0){
            final ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bytes));
            final Message message = (Message) ois.readObject();
            log.info("{}, {}, {}, {}, {}, {}", magicNum, version, serializerType, messageType, sequenceId, contentLength);
            log.info("{}", message);
            list.add(message);
        }

    }
}
